<?php
// 设置响应头
header('Content-Type: application/json');

$Uname = $_COOKIE['NAME'] ?? '';
$enorg = $_COOKIE['enorg'] ?? '';
// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit;
}

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 验证API密钥
if (!isset($data['apiKey']) || empty(trim($data['apiKey']))) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'API密钥不能为空']);
    exit;
}

$apiKey = trim($data['apiKey']);

// 写入env文件
$envContent = "ZHIPUAI_API_KEY={$apiKey}\n";
$result = file_put_contents($enorg.'-ZHIPU.env', $envContent);

if ($result === false) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '无法写入env文件']);
    exit;
}

// 成功响应
echo json_encode(['success' => true, 'message' => 'API密钥已成功保存到env文件']);
?>
